<?php

function update($data){
	# Prevent change in the username
	if(!isAdmin($_SESSION['username']) && 
		$data['username'] !== $_SESSION['username'])
		return false;

	$c = connect();
	if(_validate($data)){
		$r = _update($data);
		mysql_close($c);
		if($r)
			return true;
	}
	mysql_close($c);
	return false;
}

function getUser($idusers){
	$c = connect();
	$r = mysql_query("SELECT * FROM users WHERE idusers ='".$idusers."'");
	$data = mysql_fetch_assoc($r);
	mysql_close($c);
	return _formatfield($data);
}

function getNewUser($username){
	$c = connect();
	$r = mysql_query("SELECT * FROM newcommers WHERE username ='".$username."'");
	$data = mysql_fetch_assoc($r);
	mysql_close($c);
	return _formatfield($data);
}

function _formatfield($data){
	$field = array(
		"username", "password",
		"first_name", "last_name", 
		"email", "country", 
		"organization", "department"
	);
	foreach($field as $e){
		if(!isset($data[$e]) || $data[$e] == null)
			$data[$e] = "";
	}
	return $data;
}

function _validate($data){
	$valid = true;
	$valid &= isset($data['username']);
	$valid &= isset($data['password']) && (sizeof($data['password'])>0);
	$valid &= isset($data['first_name']);
	$valid &= isset($data['last_name']);
	$valid &= isset($data['email']);

	$r = mysql_query("SELECT * FROM users, newcommers 
		WHERE email = '".$data['email']."'");
	$valid &= mysql_num_rows($r)==0;
	return $valid;
}

function _update($data){
	$param = array(
		"username" => $data['username'],
		"password" => $data['password'],
		"first_name" => $data['first_name'],
		"last_name" => $data['last_name'],
		"email" => $data['email'],
	);

	if(strlen($data['country'])>2)
		$param['country'] = $data['country'];
	if(strlen($data['organization'])>2)
		$param['organization'] = $data['organization'];
	if(strlen($data['department'])>2)
		$param['department'] = $data['department'];
	
	if(isset($_SESSION['username']) && !isset($_SESSION['idusers'])){
		# new user
		$query = "INSERT INTO users (".implode(",", array_keys($param)).") 
			VALUES ('".implode("','", array_values($param))."')";
		$remove = "DELETE FROM newcommers WHERE username='".$param['username']."'";
	}
	else{
		# user
		$comb = "";
		foreach($param as $k => $v)
			$comb .= $k."='".$v."',";
		$comb = substr_replace($comb, "", -1);
		$query = "UPDATE INTO users SET $comb WHERE username = '".$param['username']."'";
	}

	mysql_query($query);
	if(isset($remove))
		mysql_query($remove);
}
?>
